#!/usr/bin/env python
import atlasgen as atl
import cPickle
import string
import sys

#load template-->generate atlas
#add next graph to list--->rotate graph in atlas--->
#save rotated graph back to its file--->generate atlas from graph list
#repeat until all graphs are in atlas

def main():

	#setup
	fo = file('atlas_list','r')
	atlaslist = fo.readlines()		#atlaslist= [line1\n, line2\n, line3\n...]
	fo.close()

	for line in range(len(atlaslist)):
		atlaslist[line] = atlaslist[line].split('\n')[0]	#line.split('\n')= ['line','\n']

	#precheck
	for line in atlaslist:
		gfo = file(line,'rb')
		print gfo
		graph = cPickle.load(gfo)
		og = graph['orderedGraphs'][(1,'mp_graphs')]
		nodes = og.nodes(data=True)
		for n in nodes:
			if n[1]['rank'] == 0:
				if n[1]['trwcrd'].all():			#if not np.array([0,0,0])
					print 'precheck failed for:',line
					print n[1]['trwcrd']
					return 1
				else:
					print 'precheck cleared for:',line
					break
	graphlist = []
	for line in range(len(atlaslist)):						
		
		#update graphlist
		graphlist.append(atlaslist[line])	

		#load
		gfo = file(graphlist[line],'rb')
		print gfo
		graph = cPickle.load(gfo)
		gfo.close()
		
		#initial instance= template graph/atlas
		if line == 0:
			atlas = atl.generate_atlas(graphlist)
			print "atlas zero", atlas
			continue

		#midcheck
		og = graph['orderedGraphs'][(1,'mp_graphs')]
		nodes = og.nodes(data=True)
		for n in nodes:
			if n[1]['rank'] == 0:
				if n[1]['trwcrd'].all():			#if not np.array([0,0,0])
					print 'midcheck failed for:',atlaslist[line]
					print n[1]['trwcrd']
					return 2
				else:
					print 'midcheck cleared for:',atlaslist[line]
					break

		print "rotating graph..."
		graph = atl.autorotate(graph,atlas,iterate = 600)	#optimize rotation
		
		#postcheck before saving graph
		og = graph['orderedGraphs'][(1,'mp_graphs')]
		nodes = og.nodes(data=True)
		for n in nodes:
			if n[1]['rank'] == 0:
				if n[1]['trwcrd'].all():			#if not np.array([0,0,0])
					print 'postcheck failed for:',atlaslist[line]
					print n[1]['trwcrd']
					return 2
				else:
					print 'postcheck cleared for:',atlaslist[line]
					break


		print "saving graph..."
		#print graph['orderedGraphs'][(1,'mp_graphs')].nodes(data=True)
		gfo = file(graphlist[line],'wb')
		#print "graph file object", gfo
		cPickle.dump(graph,gfo)					#save graph back to same file before gen_atlas
		gfo.close()						#close file

		print "generating atlas..."
		atlas = atl.generate_atlas(graphlist)			
		print atlas
		
	print atlas

	#pickle atlas
	afo = file(sys.argv[1],'wb')
	cPickle.dump(atlas, afo)
	afo.close()

	return 0

if __name__== "__main__":
	main()
#-----------------------END OF PROGRAM------------------------
